﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections;
using LitJson;

namespace He.Web.Tools
{
    /// <summary>
    /// upload_json 的摘要说明
    /// </summary>
    public class upload_json : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpPostedFile imgFile = context.Request.Files["imgFile"];
            if (imgFile == null)
            {
                showError("请选择要上传文件！", context);
                return;
            }
            He.Web.UI.Upload upFiles = new He.Web.UI.Upload();
            string remsg = upFiles.fileSaveAs(imgFile);

            string pattern = @"^{\s*msg:\s*(.*)\s*,\s*msbox:\s*\""(.*)\""\s*}$"; //键名前和键值前后都允许出现空白字符
            Regex r = new Regex(pattern, RegexOptions.IgnoreCase); //正则表达式实例，不区分大小写
            Match m = r.Match(remsg); //搜索匹配项
            string msg = m.Groups[1].Value; //msg的值，正则表达式中第1个圆括号捕获的值
            string msbox = m.Groups[2].Value; //msbox的值，正则表达式中第2个圆括号捕获的值 
            if (msg == "0")
            {
                showError(msbox, context);
            }
            String fileUrl = msbox;

            Hashtable hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();
        }

        private void showError(string message, HttpContext context)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}